package home.ex.todolist.client.core;

import home.ex.todolist.client.action.GetAllTodo;
import home.ex.todolist.client.action.GetAllTodoResult;
import home.ex.todolist.client.place.NameTokens;
import home.ex.todolist.shared.Todo;

import java.util.ArrayList;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.inject.Inject;
import com.gwtplatform.dispatch.shared.DispatchAsync;
import com.gwtplatform.mvp.client.Presenter;
import com.gwtplatform.mvp.client.View;
import com.gwtplatform.mvp.client.annotations.NameToken;
import com.gwtplatform.mvp.client.annotations.ProxyCodeSplit;
import com.gwtplatform.mvp.client.proxy.ProxyPlace;
import com.gwtplatform.mvp.client.proxy.RevealRootContentEvent;

public class MainTodoPresenter extends Presenter<MainTodoPresenter.MyView, MainTodoPresenter.MyProxy> {
    
    public interface MyView extends View {
	
	public void setTodolist(final FlexTable todolist);
	
	public FlexTable getTodolist();
	
	public void setTodoData(ArrayList<Todo> todoList);
    }
    
    @ProxyCodeSplit
    @NameToken(NameTokens.main)
    public interface MyProxy extends ProxyPlace<MainTodoPresenter> {
    }
    
    @Inject
    private DispatchAsync dispatchAsync;
    
    @Inject
    public MainTodoPresenter(final EventBus eventBus, final MyView view, final MyProxy proxy) {
	super(eventBus, view, proxy);
    }
    
    @Override
    protected void revealInParent() {
	RevealRootContentEvent.fire(this, this);
    }
    
    @Override
    protected void onBind() {
	super.onBind();
    }
    
    @Override
    protected void onReset() {
	super.onReveal();
	this.dispatchAsync.execute(new GetAllTodo(), this.getAllCallback);
    }
    
    AsyncCallback<GetAllTodoResult> getAllCallback = new AsyncCallback<GetAllTodoResult>() {
	
	@Override
	public void onSuccess(final GetAllTodoResult result) {
	    GWT.log(result.getTodos().toString());
	    MainTodoPresenter.this.getView().setTodoData(result.getTodos());
	}
	
	@Override
	public void onFailure(final Throwable caught) {
	    GWT.log(caught.getMessage());
	}
    };
}
